package study.eggs.utils;

import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class FYearUtils {

    private static Date date = DateUtils.parseStdYMDate("2021-01");
//    private static Date date = DateUtils.now();

    /**
     * 获取财年起始月
     *
     * @param fYear 财年 YYYY
     */
    public static FYearDate getFYearMonthOf(int fYear) {
        Date now = DateUtils.now();
        int month = DateUtils.getMonth(now);
        Date start, end;
        if (isThisFYear(fYear)) {
            //Step-1: 本财年，结束于现在
            end = now;
            //
            if (month >= 6) {
                int year = DateUtils.getYear(now);
                start = DateUtils.parseStdYMDate(year + "-06");
            } else {
                start = DateUtils.plusMonths(now, -(month + 6));
            }
        } else {
            //已过财年，结束于5月，开始于前11个月
            end = DateUtils.parseStdYMDate(fYear + "-05");
            start = DateUtils.plusMonths(end, -11);
        }
        String startDate = DateUtils.toStdYMStr(start);
        String endDate = DateUtils.toStdYMStr(end);
        return new FYearDate(startDate, endDate);
    }

    public static boolean isThisFYear(int fYear) {
        Date now = DateUtils.now();
        int year = DateUtils.getYear(now);
        int month = DateUtils.getMonth(now);
        if (month >= 6) {
            year++;
        }
        if (fYear > year) {
            throw new IllegalStateException(String.format("未来财年[%s]", fYear));
        }
        return year == fYear;
    }

    @ToString
    @Getter
    private static class FYearDate {
        private String startDate;
        private String endDate;

        public FYearDate(String startDate, String endDate) {
            this.startDate = startDate;
            this.endDate = endDate;
        }
    }

    public static void main(String[] args) {
        int fYear = 2022;
        log.info(">>>>>> {}", getFYearMonthOf(fYear));
        log.info(">>>>>> {}", getFYearMonthOf(fYear - 1));
        log.info(">>>>>> {}", getFYearMonthOf(fYear - 2));
        log.info(">>>>>> {}", getFYearMonthOf(fYear - 3));
        log.info(">>>>>> {}", getFYearMonthOf(fYear - 4));
    }
}
